package com.tdf.webblog.handler;

import com.tdf.webblog.dao.AdminMenuDAO;
import com.tdf.webblog.entity.AdminMenu;
import com.tdf.webblog.entity.AdminRoleMenu;
import com.tdf.webblog.entity.AdminUserRole;
import com.tdf.webblog.entity.User;
import com.tdf.webblog.service.AdminRoleMenuService;
import com.tdf.webblog.service.AdminUserRoleService;
import com.tdf.webblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
public class AuthProviderHandler {

    @Autowired
    private UserService userService;

    @Autowired
    private AdminUserRoleService adminUserRoleService;

    @Autowired
    private AdminRoleMenuService adminRoleMenuService;

    @Autowired
    private AdminMenuDAO adminMenuDAO;

    @GetMapping("/getmenus/by/currentuser/remote")
    List<AdminMenu> getMenusByCurrentUserRemote(@RequestParam("username") String username){
        User user = userService.findByUsername(username);
        // Get roles' ids of current user.
        List<Integer> rids = adminUserRoleService.listAllByUid(user.getId())
                .stream().map(AdminUserRole::getRid).collect(Collectors.toList());

        // Get menu items of these roles.
        List<Integer> menuIds = adminRoleMenuService.findAllByRid(rids)
                .stream().map(AdminRoleMenu::getMid).collect(Collectors.toList());

        List<AdminMenu> menus = adminMenuDAO.findAllById(menuIds).stream().distinct().collect(Collectors.toList());

        // Adjust the structure of the menu.
        handleMenus(menus);
        return menus;
    }


    public List<AdminMenu> getAllByParentId(int parentId) {
        return adminMenuDAO.findAllByParentId(parentId);
    }

    /**
     * Adjust the Structure of the menu.
     *
     * @param menus Menu items list without structure
     */
    public void handleMenus(List<AdminMenu> menus) {
        menus.forEach(m -> {
            List<AdminMenu> children = getAllByParentId(m.getId());
            m.setChildren(children);
        });

        menus.removeIf(m -> m.getParentId() != 0);
    }
}
